import Vue from 'vue'
import App from './App.vue'
//导入路由
import router from './router'
//导入vuex
import store from "./store";
import ElementUI from 'element-ui';
import 'element-ui/lib/theme-chalk/index.css';
import 'font-awesome/css/font-awesome.css'

import { postRequest } from "./utils/api";
import { getRequest } from "./utils/api";
import { putRequest } from "./utils/api";
import { deleteRequest } from "./utils/api";
import { downloadRequest } from "./utils/download";
import { initMenu } from "./utils/menus";


Vue.config.productionTip = true
Vue.use(ElementUI, {size: 'small'});

//全局使用请求
Vue.prototype.postRequest = postRequest
Vue.prototype.getRequest = getRequest
Vue.prototype.putRequest = putRequest
Vue.prototype.deleteRequest = deleteRequest
Vue.prototype.downloadRequest = downloadRequest

//每次调用路由都会向触发该函数
//配置路由前置守卫，路由信息从数据库中获取存放在Vuex中，在页面刷新后Vuex中路由信息初始化为null,页面可能丢失路由链接信息
router.beforeEach(((to, from, next) => {
  //to：前往的地址，form：来自的地址，next：放行钩子函数，可自定义跳转路径
  //判断用户是否登录，以此来判断是否要初始化菜单
  if (window.sessionStorage.getItem('token')){
    //初始化菜单，并放行
    initMenu(router, store)
    //判断用户信息是否存在
    if (!window.sessionStorage.getItem('user')){
      return getRequest('/admin/info').then(res => {
        if (res){
          //存储用户信息
          window.sessionStorage.setItem('user', JSON.stringify(res))
          store.commit('INIT_ADMIN', res)
          //登录时传递to参数，replace: true，解决无参时登录两次的问题
          next({...to, replace: true})
        }
      })
    }
    next()
  } else {
    //判断用户前往的页面，根据路径判断是否登录
    if (to.path === '/'){
      next()
    }else {
      //未登录的话就重定向到登录页面，并在后面加登录后要跳转的地址
      next('/?redirect=' + to.path)
    }
  }
}))


new Vue({
  router,
  store,
  render: h => h(App)
}).$mount('#app')
